const fs = require("fs");
const path = require("path");
const { dirU } = require("./common");

/**
 * 删除文件
 * @param {*} path
 */
function delDir(path) {
  let files = [];
  if (fs.existsSync(path)) {
    files = fs.readdirSync(path);
    for (let file of files) {
      let curPath = path + dirU + file;
      if (fs.statSync(curPath).isDirectory()) {
        delDir(curPath);
      } else {
        fs.unlinkSync(curPath);
      }
    }
    fs.rmdirSync(path);
  }
}

/**
 * 递归创建文件夹
 * @param {*} path
 */
function mkdirpSync(path) {
  if (!path) {
    return;
  }
  if (!fs.existsSync(path)) {
    //mkdirpSync(path.substring(0, path.lastIndexOf("/")));
    fs.mkdirSync(path, { recursive: true });
  }
}

async function copyDir(src, dest, pipeFn) {
  if (!fs.existsSync(dest)) mkdirpSync(dest);
  const items = fs.readdirSync(src);
  for (const item of items) {
    const srcPath = path.join(src, item);
    const destPath = path.join(dest, item);
    const stat = fs.statSync(srcPath);
    if (stat.isDirectory()) {
      await copyDir(srcPath, destPath, pipeFn);
    } else {
      await fs.copyFileSync(srcPath, destPath);
      if (pipeFn) {
        await pipeFn(destPath);
      }
    }
  }
}

module.exports = {
  delDir,
  mkdirpSync,
  copyDir,
};
